<template>
  <div class="customer-adjustment-wrap">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput ref="paramsObj" v-model="paramsObj" :filter-list="filterList" is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div style="position: absolute;left: 509px;top: 6px;display:flex;align-items:center;">
          <el-checkbox v-model="isShowMe" style="margin-right: 20px;" @change="queryClick">我发起的</el-checkbox>
          <el-checkbox v-if="tabStatus !== -2" v-model="isMyApproval" @change="queryClick">我审批的</el-checkbox>
          <el-checkbox v-model="isMyPending" @change="queryClick">待我处理</el-checkbox>
        </div>
        <div class="opeator-bar">
          <createBtn v-if="hasRouteAuth('crm:customerAdjustment:create')" style="margin-right: 10px;" @click.native="toCreate"/>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="moreOperatorList"
          />
        </div>
      </div>
      <div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            :row-class-name="tableRowClassName"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
              <template slot-scope="scope" slot="header">
                <div class="diyHeader">{{ scope.column.label }}</div>
              </template>
              <template slot-scope="scope">
                <processSn :is-expedited="scope.row.isExpedited">
                  <div v-if="scope.row.approvalNo" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                    <ToolTip :content="handleSnNumber(scope.row.approvalNo)" placement="top-start" is-can-click @handelClick="toDetail(scope.row)" />
                  </div>
                  <div v-else>--</div>
                </processSn>
              </template>
            </u-table-column>
            <u-table-column align="left" label="客户名称" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.customer" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="客户等级" min-width="120" class-name="cell-bg-box" prop="customerLevel" sortable="custom">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.customerLevel" :open-delay="800" placement="top">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.customerLevel }}</div>
                  <span
                    :style="{color: scope.row.levelColor || '#333', background: scope.row.levelColor ? changeColorAlphaVal(scope.row.levelColor, 0.14) : 'transparent'}"
                    class="ellipsisOne text-bg">
                    {{ scope.row.customerLevel }}
                  </span>
                </el-tooltip>
                <div
                  v-else
                  :style="{color: scope.row.levelColor || '#333', background: scope.row.levelColor ? changeColorAlphaVal(scope.row.levelColor, 0.14) : 'transparent'}"
                  class="text-bg">--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请说明" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.description" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请范围" min-width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.ranges || '--' }}</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人" min-width="80">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column :min-width="handleTdWidth(120,150)" align="left" label="当前处理人">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.currentHandler" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前节点" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.currentNode" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.status || scope.row.status===0" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content">{{ scope.row.status | statusFilter }}</div>
                  <StatusText
                    :color="['#FFBC3D', '#FD8546', '#FF4E5F', '#999', '#31CC9C', '#406EFF'][scope.row.status]"
                    :text="scope.row.status | statusFilter"
                  />
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请部门" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.proposerDepartment" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.subordinateDepartment" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="flex-center">
                  <div v-if="scope.row.status !== 0 && !showMobilePage" class="button-text br" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {
                        label: '查看',
                        handelClick: () => {toDetail(scope.row)},
                        auth: scope.row.status !== 0 && showMobilePage
                      },{
                        label: '复制',
                        handelClick: () => {handlerCreateNew(scope.row)},
                        disabled: scope.row.status === 0 || !hasRouteAuth('crm:customerAdjustment:create')
                      },{
                        label: '编辑',
                        handelClick: () => {toEdit(scope.row)},
                        disabled: setEditDisable(scope.row)
                      },{
                        label: '删除',
                        handelClick: () => {toDelete(scope.row)},
                        disabled: setDelDisable(scope.row)
                    }]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus">
              <div slot="checkGroup">
                <el-checkbox v-model="isMyPending" style="margin-right: 20px;" @change="queryClick" >待我处理</el-checkbox>
                <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
                <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
              </div>
            </FilterInput>
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="moreOperatorList"
              show-mobile-icon
            />
            <createBtn mobile-table @click.native="toCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
        <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
        <ApproverChange ref="approverChangeDialog" :business-type="BUSINESS_TYPE.CUSTOMER_ADJUSTMENT" :ids="curSelectedId" @changeCallBack="changeCallBack"/>
      </div>
    </div>
  </div>
</template>

<script>
// compoments
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import ListTab from '@/components/ListTab';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
// api
import { CURRENT_NODE_MODULE } from '@/utils/const';
import { getDepartmentAll } from '@/api/config';
import { getDepartmentList } from '@/api/select';
import { getClientAdjustmentList, getClientAdjustmentTabs, delClientAdjustment, getLevelList } from '@/api/customer';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import schedule from '@/mixins/schedule';
import approverChange from '@/mixins/approverChange';
import copyLink from '@/mixins/copyLink';
import filterObjStoreMixin from '@/mixins/filterObjStore';
// tools
import axios from 'axios';
import { hasRouteAuth } from '@/utils/permission';
import { format } from '@/filters/date';
import { paramsAryToStr, paramsRangeFormat } from '@/utils/paramsFormat';
import { expeditedOptions } from '@/filters/status';
import { PROCESS_TYPE } from '@/utils/const/process';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';
import { LEVEL_CHANGE_TYPE } from '@/utils/const/customer';
import { changeColorAlphaVal } from '@/utils/tools';

export default {
  components: {
    EmptyPlaceholder, DiversAuditorDialog,
    createBtn, btnGroup, ListTab, MoreOpeator
  },
  filters: {
    statusFilter(status) {
      return {
        0: '草稿中',
        1: '审批中',
        2: '未过审',
        3: '已作废',
        4: '已完成',
        5: '待提交'
      }[status] || '--';
    }
  },
  mixins: [tableSelections, TableAdaptive, mobileTable, schedule, approverChange, copyLink, filterObjStoreMixin],
  data() {
    return {
      sortType: '',
      sortName: '',
      paramsObj: {},
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false,
      tabs: [],
      tabStatus: -1,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      perPage: 20,
      listLoading: false,
      page: 1,
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      clientLevelOptions: [],
      departmentOption: [],
      deptTreeList: [],
      cancelToken: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        // 输入框
        { keyword: 'approvalNo', name: '审批单号', labelWidth: '85px', type: 'input' },
        { keyword: 'customer', name: '客户名称', labelWidth: '85px', type: 'input' },
        { keyword: 'description', name: '申请说明', labelWidth: '85px', type: 'input' },
        { keyword: 'proposer', name: '申请人', labelWidth: '85px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '85px', type: 'input' },
        { keyword: 'currentHandler', name: '当前处理人', labelWidth: '85px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '85px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '85px' },
        // 下拉框
        { keyword: 'customerLevel', name: '客户等级', type: 'select', valueName: 'value', options: this.clientLevelOptions },
        { keyword: 'ranges', name: '申请范围', type: 'select', valueName: 'value', options: this.applyRangeOptions },
        { keyword: 'status', name: '状态', type: 'select', options: this.statusList },
        { keyword: 'applyDepartmentId', name: '申请部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'subordinateDepartmentId', name: '所属部门', type: 'select', isSearch: true, options: this.departmentOption },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.CUSTOMER_ADJUSTMENT },
          labelName: 'name',
          placeholder: '当前节点',
          searchkeyword: 'keyword',
          apiUrl: 'admin/common/currentNodes'
        },
        // 日期
        { keyword: 'createTime', name: '创建时间', labelWidth: '85px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    statusList() {
      return [
        { value: 0, label: '草稿中' },
        { value: 1, label: '审批中' },
        { value: 2, label: '未过审' },
        { value: 3, label: '已作废' },
        { value: 4, label: '已完成' },
        { value: 5, label: '待提交' }
      ];
    },
    applyRangeOptions() {
      return [
        { value: LEVEL_CHANGE_TYPE.LEVEL, label: '调整等级' },
        { value: LEVEL_CHANGE_TYPE.AMOUNT, label: '调整额度' },
        { value: LEVEL_CHANGE_TYPE.PERIOD, label: '调整账期' }
      ];
    },
    rangeKeyArr() {
      return [
        { attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time', addTime: true }
      ];
    },
    arrayKeyArr() {
      return ['applyDepartmentId', 'subordinateDepartmentId', 'currentNode'];
    },
    moreOperatorList() {
      return [
        { label: '批量导出', exportApi: `admin/customerAdjustment/export`, auth: hasRouteAuth('crm:customerAdjustment:batchExport'), type: 'export', exportName: '客户调额申请', isBeforeExport: true, beforeExport: this.exportBeforeExport, refName: 'clientAdjustmentExportRef' },
        { label: '批量抄送', handelClick: this.handleSendMsg },
        { label: '复制链接', handelClick: this.batchCopyLink },
        { label: '批量转交', handelClick: () => this.handleBatchApproverChange(this.BUSINESS_TYPE.CUSTOMER_ADJUSTMENT) }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 150 : 192;
    }
  },
  created() {
    this.queryDeptTreeList();
    this.queryClientLevelOptions();
    this.getDepartment();
    this.fetchData();
  },
  methods: {
    format,
    hasRouteAuth,
    changeColorAlphaVal,
    queryClick() {
      this.fetchData(true);
    },
    getDepartment() {
      getDepartmentList({ type: 1 }).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.departmentOption = res.data;
        }
      }).catch((err) => {
        console.error(err);
      });
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.fetchData(true);
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.tabStatus = this.tabStatus;
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortType = this.sortType || '';
      params.sortName = this.sortName || '';
      return params;
    },
    queryTabs() {
      const params = this.formatParams();
      getClientAdjustmentTabs(params).then(res => {
        if (res.code === 200) {
          this.tabs = res.data;
        }
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}#/client/customerAdjustmentDetail?id=${item.id}&processId=${item.processId}`;
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.listLoading = true;
      this.queryTabs();
      if (reset) this.page = 1;
      const params = this.formatParams();
      getClientAdjustmentList(params, source.token).then(res => {
        if (res.code === 200) {
          this.list = res.data;
          this.listLoading = false;
        }
        if (this.setSelectRow) this.setSelectRow(res.data.items);
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        console.error(err.message);
      });
    },
    toCreate() {
      this.$router.push({
        name: 'customerAdjustmentCreate'
      });
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    // 获取客户等级列表
    // 客户等级
    queryClientLevelOptions() {
      getLevelList().then(res => {
        const result = res && res.data || [];
        result.forEach(item => {
          item.label = item.name;
          item.value = item.name;
        });
        this.clientLevelOptions = result;
      }).catch(e => {
        console.log(e);
      });
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'clientAdjustmentExportRef');
      }
    },
    setEditDisable(data) {
      return !(data.status === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5];// 草稿、已作废、未过审、待提交
      return !(statusArr.includes(data.status) && (data.creatorId === this.userInfo.id || this.hasRouteAuth('crm:customerAdjustment:delete')));// 除审批中和已完成状态且为创建人或者有删除权限
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.CUSTOMER_ADJUSTMENT);
      this.$router.push({
        name: 'customerAdjustmentDetail',
        query: {
          id: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
    },
    handlerCreateNew(row) {
      const routeUrl = this.$router.resolve({
        name: 'customerAdjustmentEdit',
        params: { id: row.id },
        query: { reapplyId: row.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    },
    toEdit(row) {
      this.$router.push({
        name: 'customerAdjustmentEdit',
        params: {
          id: row.id
        }
      });
    },
    toDelete(row) {
      showModal('是否确定删除?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        delClientAdjustment(row.id).then(_ => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.customer-adjustment-wrap {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
  }
  & ::v-deep {
    .pointer {
      cursor: pointer;
    }
    .cell-bg-box > .cell {
      height: 20px;
    }
  }
  .opeator-bar {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    align-items: center;
  }
  .text-bg {
    padding: 0 10px;
    border-radius: 999px;
    color: #fff;
    display: inline-block;
    height: 20px;
    line-height: 20px;
    max-width: 100%;
  }
}
</style>
